﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using System.Web;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate.Tool.hbm2ddl;
using PerfilEmpreendedor.Bo.Model;

namespace PerfilEmpreendedor.Dao.Factory
{
    public class HttpModule : IHttpModule
    {
        public static readonly string CHAVE = "NHibernateSession";
        private static ISession _session;
        private static ISessionFactory factory = null;

        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(context_BeginRequest);
            context.EndRequest += new EventHandler(context_EndRequest);
        }

        public void Dispose()
        {
        }

        public static ISession GetSession
        {
            get
            {
                if (HttpContext.Current == null)
                {
                    if (_session != null)
                    {
                        return _session;
                    }
                    else
                    {
                        _session = AbrirSessao();
                        return _session;
                    }
                }
                else
                {
                    HttpContext currentContext = HttpContext.Current;
                    ISession session = currentContext.Items[CHAVE] as ISession;
                    if (session == null)
                    {
                        session = AbrirSessao();
                       
                    }
                    else if (!session.IsOpen)
                    {
                        session = AbrirSessao();
                    }
                    currentContext.Items[CHAVE] = session;
                    return session;
                }
            }
        }

        private void context_BeginRequest(object sender, EventArgs e)
        {
            HttpApplication application = (HttpApplication)sender;
            HttpContext context = application.Context;
            context.Items[CHAVE] = AbrirSessao();
        }

        private void context_EndRequest(object sender, EventArgs e)
        {
            HttpApplication application = (HttpApplication)sender;
            HttpContext context = application.Context;

            ISession session = context.Items[CHAVE] as ISession;
            if (session != null)
            {
                if (session.IsOpen)
                {
                    session.Flush();
                    session.Close();
                }
              
            }

            context.Items[CHAVE] = null;
        }

        private static ISession AbrirSessao()
        {
            ISession session;
            session = GetFactory().OpenSession();

            if (session == null)
                throw new InvalidOperationException("OpenSession() is null.");

            return session;
        }

        private static ISessionFactory GetFactory()
        {
            
            FluentConfiguration configuration = Fluently.Configure()

                .Database(MsSqlConfiguration.MsSql2008.ShowSql().ConnectionString(x => x.FromConnectionStringWithKey("DataBase")))
                .Mappings(x => x.FluentMappings.AddFromAssemblyOf<Usuario>());

            factory = configuration.BuildSessionFactory();
            return factory;
            
         
        }
        
        public static void GenerateDataBase()
        {
            Fluently.Configure()
              .Database(MsSqlConfiguration.MsSql2008.ConnectionString(x => x.FromConnectionStringWithKey("DataBase")))
                .Mappings(m =>
                    m.FluentMappings.AddFromAssemblyOf<Usuario>())
                    .ExposeConfiguration(cf => new SchemaExport(cf).Create(true, true))
                .BuildSessionFactory();

           
        }

        public static Int32 ResetDatabase()
        {
            ISession session = GetSession;
            StringBuilder strSql = new StringBuilder();
            strSql.Append("Delete from Acao;");
            strSql.Append("Delete from DicasToHistoricos;");
            strSql.Append("Delete from PartidaUsuario;");
            strSql.Append("Delete from Historico;");
            strSql.Append("Delete from Partida;");
            strSql.Append("Delete from Dica;");
            strSql.Append("Delete from Cartela;");
            strSql.Append("Delete from Usuario where Login<>'Admin';");
            ISQLQuery query = session.CreateSQLQuery(strSql.ToString());
            return query.ExecuteUpdate();
        }

    }
}
